package com.lysj.admin.gateway.filter;

import com.lysj.admin.gateway.constants.GatewayConstants;
import com.lysj.admin.gateway.feign.AuthFeign;
import com.lysj.admin.utils.exception.BaseException;
import com.lysj.admin.utils.json.JacksonUtil;
import com.lysj.admin.utils.web.Resp;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Created by zk on 2019-01-02 17:15
 * @description
 */
public class AuthFilter extends MyAbstractPreZuulFilter {
    @Resource
    private AuthFeign authFeign;
    @Value("${secret.header}")
    private String header;


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 4;//数字越大越靠后
    }

    @Override
    public boolean shouldFilter() {
        if(!super.shouldFilter()){
            return false;
        }
        if("auth".equals(getIssName())){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Resp resp = authFeign.authentication(getToken(),request.getRequestURI());
        if(!resp.getCode().equals(Resp.Status.SUCCESS.getCode())){
            request.setAttribute(GatewayConstants.IS_SUCCESS_NAME,false);
            ctx.setSendZuulResponse(false);
            ctx.setResponseBody(JacksonUtil.toJson(resp));
            ctx.getResponse().setContentType("application/json; charset=utf-8");
            return null;
        }
        ctx.getResponse().setHeader(header,resp.getObj().toString());
        return null;
    }


}
